package com.laowang.common.utils.wxCryptUtil;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;

public class EncryptUtils {

    public static String decryptWXAES(String data, String key, String iv, String encodingFormat){
        Security.addProvider(new BouncyCastleProvider());
        //被加密的数据
        byte[] dataByte = org.apache.commons.codec.binary.Base64.decodeBase64(data);
        //加密秘钥
        byte[] keyByte = org.apache.commons.codec.binary.Base64.decodeBase64(key);
        //偏移量
        byte[] ivByte = org.apache.commons.codec.binary.Base64.decodeBase64(iv);

        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, encodingFormat);
                return result;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
